package com.leanit.pmc.center.user;

import com.sdeport.common.vo.OrganizationVO;
import com.sdeport.common.vo.UserVO;
import com.sdeport.security.shiro.SDUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户登录controller
 *
 * @author
 */
@Controller
@RequestMapping("/user")
public class UserController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    //    private EnterpriseService enterpriseService;
    @Value("${shiro.login.url}")
    private String loginUrl;
    @Value("${index.url}")
    private String indexUrl;

    @RequestMapping(value = "/getSessionUser", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public UserInfo getSessionUser(HttpSession session) {
        UserInfo userVo = getUserInfo();
        session.setAttribute("UserInfo", userVo);
        session.setAttribute("loginUrl", loginUrl);
        session.setAttribute("indexUrl", indexUrl);
        return userVo;
    }

    private UserInfo getUserInfo() {
        UserInfo userVo = new UserInfo();
        //4px提供的jar包，从session中取到用户对象
        try {
            UserVO currentUser = SDUtils.getCurrentUser();
            String username = currentUser.getUsername();
            String departmentId = currentUser.getDepartmentId();
            String companyId = currentUser.getCompanyId();
            String companyName = currentUser.getCompanyName();
            String cnName = currentUser.getCnName();
            String email = currentUser.getEmail();
            String phone = currentUser.getMobilePhoneNumber();
            logger.error("===========username========{}", username);

            if (currentUser.getOrganizationJobs() != null && currentUser.getOrganizationJobs().size() > 0) {
                OrganizationVO organizationVO = currentUser.getOrganizationJobs().get(0).getOrganization();
                if (organizationVO != null) {
                    String organizationCode = organizationVO.getOrganizationCode();
                    if (StringUtils.isNotEmpty(organizationCode)) {
                        userVo.setOrganizationCode(organizationCode);
                    }
                }
            }
            if (StringUtils.isNotEmpty(username)) {
                userVo.setLogName(username);
                userVo.setName(username);
            }
            if (StringUtils.isNotEmpty(departmentId)) {
                userVo.setOrganizationId(departmentId);
            }
            if (StringUtils.isNotEmpty(companyId)) {
                userVo.setOrganizationId(companyId);
                userVo.setCompanyId(companyId);
            }
            if (StringUtils.isNotEmpty(companyName)) {
                userVo.setCompany(companyName);
            }
            if (StringUtils.isNotEmpty(cnName)) {
                userVo.setName(cnName);
            }
            if (StringUtils.isNotEmpty(email)) {
                userVo.setEmail(email);
            }
            if (StringUtils.isNotEmpty(phone)) {
                userVo.setPhone(phone);
            }
        } catch (Exception e) {
            logger.error("", e);
            userVo.setLogName("error");
            userVo.setOrganizationId("111111");
            userVo.setName("超级管理员");
            userVo.setCompany("山东海运船舶管理有限公司");
        }
        return userVo;
    }

    @RequestMapping(value = "/editPasswd", method = {RequestMethod.GET, RequestMethod.POST})
    public String editPasswd() {
        return "user/changePassword";
    }

    /**
     * 判断当前登陆的用户是会否有登陆的权限
     * vehicle_role_login
     * cargo_role_login
     * ecommerce_role_login
     * portal_role_login
     *
     * @param roleIdentifier
     * @return
     */
    @RequestMapping(value = "/hasRole", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public boolean hasRole(String roleIdentifier) {
        try {
            return SecurityUtils.getSubject().hasRole(roleIdentifier);
        } catch (Exception e) {
            return false;
        }
    }

    /***
     * @param roleIdentifiers
     * @return
     */
    public boolean hasRoles(List<String> roleIdentifiers) {
        return SecurityUtils.getSubject().hasAllRoles(roleIdentifiers);

    }


    /***
     * 获取所有权限
     *
     * @return rightsMap
     */
    @RequestMapping(value = "/getAllRoles", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map<String, Boolean> getAllRoles() {
        Map<String, Boolean> rightsMap = new HashMap<>();
        String[] roles = {"cargo_role_login", "vehicle_role_login", "ecommerce_role_login"};

        for (String role : roles) {
            rightsMap.put(role, hasRole(role));
        }
        return rightsMap;
    }

    @RequestMapping(value = "/getUserInfoDetail", method = {RequestMethod.GET, RequestMethod.POST})
    public String getUserInfoDetail() {
        return "register_view";
    }
}
